import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  zoneManagementApi, 
  zoneApi, 
  buildingApi, 
  communityApi 
} from '@/api/region/zone'
import { 
  CommunityEntryState, 
  Zone, 
  Building, 
  ZoneDrawingData, 
  ZoneSaveData, 
  ZoneManagementInitialData, 
  CommunityInfo, 
  LoadingState,
  ZoneManagementEvents
} from '@/types/zone'
import mitt from '@/utils/mitt'

/**
 * 分区管理状态管理
 */
export const useZoneManagementStore = defineStore('zoneManagement', () => {
  // 状态
  const communityInfo = ref<CommunityInfo | null>(null)
  const buildingList = ref<Building[]>([])
  const zoneList = ref<Zone[]>([])
  const drawingData = ref<ZoneDrawingData | null>(null)
  const communityEntryState = ref<CommunityEntryState>({
    isFirstEntry: true,
    hasExistingZones: false,
    zoneCount: 0
  })
  const operationMode = ref<'CREATE' | 'UPDATE'>('CREATE')
  const loadingState = ref<LoadingState>({
    isLoading: false,
    progress: 0,
    message: '',
    stage: 'init'
  })

  // 计算属性
  const availableBuildings = computed(() => {
    return buildingList.value.filter(building => building.status === 'available')
  })

  const usedBuildings = computed(() => {
    return buildingList.value.filter(building => building.status === 'used')
  })

  const getOperationMode = computed(() => operationMode.value)

  const showWelcomeMessage = computed(() => communityEntryState.value.isFirstEntry)

  const showDataRecoveryMessage = computed(() => 
    !communityEntryState.value.isFirstEntry && 
    communityEntryState.value.hasExistingZones
  )

  // 动作
  /**
   * 判断社区进入状态
   */
  const determineEntryState = async (communityId: number): Promise<CommunityEntryState> => {
    try {
      const response = await zoneManagementApi.determineCommunityEntryState(communityId)
      if (response.code === 200) {
        const state = response.data
        communityEntryState.value = {
          isFirstEntry: state.firstEntry,
          hasExistingZones: state.hasExistingZones,
          zoneCount: state.zoneCount,
          lastModifiedTime: state.lastModifiedTime
        }
        
        // 根据状态设置操作模式
        operationMode.value = state.firstEntry ? 'CREATE' : 'UPDATE'
        
        return communityEntryState.value
      } else {
        throw new Error(response.message || '判断社区进入状态失败')
      }
    } catch (error) {
      console.error('判断社区进入状态失败:', error)
      // 默认按初次进入处理
      communityEntryState.value = {
        isFirstEntry: true,
        hasExistingZones: false,
        zoneCount: 0
      }
      operationMode.value = 'CREATE'
      return communityEntryState.value
    }
  }

  /**
   * 加载分区管理初始数据
   */
  const loadInitialData = async (communityId: number): Promise<ZoneManagementInitialData> => {
    loadingState.value.isLoading = true
    loadingState.value.progress = 0
    loadingState.value.stage = 'init'
    
    try {
      loadingState.value.stage = 'community'
      loadingState.value.message = '正在加载社区信息...'
      loadingState.value.progress = 20
      
      // 并行加载基础数据
      const [communityResponse, buildingResponse, zoneResponse] = await Promise.all([
        communityApi.getCommunityDetail(communityId),
        buildingApi.getBuildingsByCommunity(communityId),
        zoneApi.getZonesByCommunity(communityId)
      ])
      
      loadingState.value.stage = 'buildings'
      loadingState.value.message = '正在处理楼栋数据...'
      loadingState.value.progress = 40
      
      // 处理社区信息
      if (communityResponse.code === 200 && communityResponse.data) {
        communityInfo.value = communityResponse.data
      } else {
        throw new Error('加载社区信息失败')
      }
      
      // 处理楼栋列表
      if (buildingResponse.code === 200) {
        buildingList.value = buildingResponse.data.map((building: any) => ({
          ...building,
          status: 'available' as const
        }))
      } else {
        throw new Error('加载楼栋列表失败')
      }
      
      loadingState.value.stage = 'zones'
      loadingState.value.message = '正在加载分区信息...'
      loadingState.value.progress = 60
      
      // 处理分区列表
      if (zoneResponse.code === 200) {
        zoneList.value = zoneResponse.data || []
      } else {
        throw new Error('加载分区列表失败')
      }
      
      // 如果有分区数据，加载绘图数据
      let drawingDataResult = null
      if (zoneList.value.length > 0) {
        loadingState.value.stage = 'drawing'
        loadingState.value.message = '正在加载绘图数据...'
        loadingState.value.progress = 80
        
        try {
          const drawingResponse = await zoneManagementApi.getInitialData(communityId)
          if (drawingResponse.code === 200 && drawingResponse.data?.drawingData) {
            drawingDataResult = drawingResponse.data.drawingData
            drawingData.value = drawingDataResult
            
            // 处理楼栋状态
            if (drawingDataResult.buildings) {
              processBuildingStatus(drawingDataResult.buildings)
            }
          }
        } catch (error) {
          console.warn('加载绘图数据失败，使用默认数据:', error)
        }
      }
      
      loadingState.value.stage = 'complete'
      loadingState.value.message = '正在初始化页面...'
      loadingState.value.progress = 100
      
      const result: ZoneManagementInitialData = {
        communityInfo: communityInfo.value,
        buildingList: buildingList.value,
        zoneList: zoneList.value,
        drawingData: drawingDataResult
      }
      
      return result
    } catch (error) {
      console.error('加载初始数据失败:', error)
      ElMessage.error('加载数据失败，请刷新页面重试')
      throw error
    } finally {
      loadingState.value.isLoading = false
    }
  }

  /**
   * 处理楼栋状态
   */
  const processBuildingStatus = (buildingPositions: any[]) => {
    buildingPositions.forEach(position => {
      const building = buildingList.value.find(b => b.id === position.id)
      if (building) {
        building.status = 'used'
        building.zoneId = position.zoneId
        building.positionX = position.positionX
        building.positionY = position.positionY
      }
    })
  }

  /**
   * 保存分区管理数据
   */
  const saveZoneData = async (saveData: ZoneSaveData) => {
    try {
      const response = await zoneManagementApi.saveZoneData(saveData)
      if (response.code === 200) {
        ElMessage.success('保存成功')
        
        // 保存成功后，更新状态为非初次进入
        communityEntryState.value.isFirstEntry = false
        operationMode.value = 'UPDATE'
        
        // 重新加载数据
        await loadInitialData(saveData.communityId)
        
        return response
      } else {
        throw new Error(response.message || '保存失败')
      }
    } catch (error) {
      console.error('保存分区数据失败:', error)
      ElMessage.error('保存失败，请重试')
      throw error
    }
  }

  /**
   * 重置状态
   */
  const resetState = () => {
    communityInfo.value = null
    buildingList.value = []
    zoneList.value = []
    drawingData.value = null
    communityEntryState.value = {
      isFirstEntry: true,
      hasExistingZones: false,
      zoneCount: 0
    }
    operationMode.value = 'CREATE'
    loadingState.value = {
      isLoading: false,
      progress: 0,
      message: '',
      stage: 'init'
    }
  }

  return {
    // 状态
    communityInfo,
    buildingList,
    zoneList,
    drawingData,
    communityEntryState,
    operationMode,
    loadingState,
    
    // 计算属性
    availableBuildings,
    usedBuildings,
    getOperationMode,
    showWelcomeMessage,
    showDataRecoveryMessage,
    
    // 动作
    determineEntryState,
    loadInitialData,
    saveZoneData,
    resetState
  }
})
